package cc.ufinity.networkdiagnose.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.SimpleFTP;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.view.R;

public class FtpTestWidget extends GeneralTestWidget {

    private Activity ctx;
    private LinearLayout ftpTestChartLayout;
    private Button backBtn;
    private ScrollView scrView;
    private LinearLayout ftpTestDetail;
//    private String localFilePath = Environment.getExternalStorageDirectory() + "/ftptest/";
    private String localFilePath = "";
    private String remotePathUp ;
    private String remotePathDown = "/ftp/";
	//private String fileName = "ftp_test.png";
    private String fileNameDown = "2M.rar";
	private String fileNameUp = "1.doc";
    private ImageView pointImageView;
	private TextView timesView;
	private TextView timeRateView;
	private TextView sucRateView;
    private static final int COUNT = 10;
    private int testedTimes;
    private int testedTimesUp = 0;
    private int testedTimesDown = 0;
    private float lastSpeed=0;
    private Handler ftpTestHandler;
    private boolean logouting= false;
    private TextView uploadTextId;
    private TextView downTextId;
    private WlanManager wlanManager;
    private float lastLast;
    private SimpleFTP simpleFTP;
    private TelManager tm;
    private LinearLayout llChart; 
    
    public FtpTestWidget(Activity context) {
        super(context);
        this.ctx = context;
        remotePathUp = "/ftptest/"+ getTelNumber()+"/";
        localFilePath =  ctx.getFilesDir().getParent()+ File.separator + "ftptest" + File.separator;
        inflate(ctx, R.layout.ftp_test_widget, this);
        ftpTestChartLayout = (LinearLayout) this.findViewById(R.id.ftpTestChartLayout);
        backBtn = (Button) this.findViewById(R.id.ftp_test_btnback);
        scrView = (ScrollView) this.findViewById(R.id.ftp_test_ScrView);
        ftpTestDetail = (LinearLayout) this.findViewById(R.id.ftp_test_detail);
        pointImageView = (ImageView)findViewById(R.id.pointImageView);
        uploadTextId = (TextView)findViewById(R.id.uploadTextId);
        downTextId = (TextView)findViewById(R.id.downTextId);
        timeRateView = (TextView)findViewById(R.id.timeRateView);
        timesView = (TextView)findViewById(R.id.timesView);
        sucRateView = (TextView)findViewById(R.id.sucRateView);
        timeRateView.setText("0 Kb/s");
        timesView.setText(testedTimes+"/"+COUNT * 2+"次");
        sucRateView.setText("0 Kb/s");
      //  btnRetest = (Button) findViewById(R.id.btn_ftp_retest);
        llChart = (LinearLayout)findViewById(R.id.chart);
        bindView();
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // back(ctx);
            	try {
            		simpleFTP.setStop(true);
					simpleFTP.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
             	switch(GlobalApp.nowNetType) {
 				case 1:
 					backToTestWidget_Wlan(ctx);
 					break;
 				case 2:
 					backToTestWidget_TD(ctx);
 					break;
 				case 3:
 					backToTestWidget_GSM(ctx);
 					break;
 				default:
 					break;
 				}
             }
        });

        ftpTestHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.FTP_UPLOAD_DONE:
                	//System.out.println(wlanManager.checkNetworkType()+"  ftp 1===========wlanManager.checkNetworkType()");
                    updateUploadProgress();
                    break;
                case MessageWhat.FTP_DOWNLOAD_DONE:
                	//System.out.println(wlanManager.checkNetworkType()+"  ftp 2===========wlanManager.checkNetworkType()");
                    updateDownloadProgress();
                    break;
                case MessageWhat.DONE:
                    updateTestResult();
//                    drawLineChart();
                    break;
                case MessageWhat.FTP_CONNECT_TIMEOUT:
//                    drawLineChart();
                    showMessage(ctx, "FTP连接超时.");
                	dismissMessageDialog();
                    break;
                case MessageWhat.NETWORK_INVALID:
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    showMessage(ctx, "无法获取FTP账号");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    showMessage(ctx, "上传失败");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    showMessage(ctx, "FTP登录失败");
                	dismissMessageDialog();
                    break;
                    
                case SimpleFTP.CONNECTSUCCEED:
                	System.out.println("--------simpleFTP连接成功");
                	/*if(msg.arg1 > 0) {
                        showProgressDialog(ctx, "正在进行FTP测试...", msg.arg1);
                	} else {
                		showMessage(ctx, "simpleFTP连接成功");
                	}*/
                	break;
                case SimpleFTP.UPLOAD:
                	dismissMessageDialog();
                	setDialogProgress(simpleFTP.getCompletedSize());
                	updateUploadProgress();
                	//System.out.println("--------simpleFTP实时上传速度：" + simpleFTP.getNowUpSpeed());
                	break;
                case SimpleFTP.DOWNLOAD:
                	dismissMessageDialog();
                	setDialogProgress(simpleFTP.getCompletedSize());
                	updateDownloadProgress();
                	//System.out.println("--------simpleFTP实时下载速度：" + simpleFTP.getNowDownSpeed());
                	break;
                case SimpleFTP.UPOVER:
                	setDialogProgress(0);
                	break;
                case SimpleFTP.DOWNOVER:
                    updateTestResult();
                    drawLineChart();
                	break;
                case SimpleFTP.TIMEOUTUP:
                	dismissMessageDialog();
                    //上传超时
                	StringBuffer sb = new StringBuffer();
                    sb.append("上传超时");
                    TextView tv = new TextView(ctx);
                    tv.setTextSize(12);
                    tv.setText(sb);
                    tv.setTextColor(Color.BLACK);
                    ftpTestDetail.addView(tv);
                	break;
                case SimpleFTP.TIMEOUTDOWN:
                	//下载超时
                	dismissMessageDialog();
                	StringBuffer sb2 = new StringBuffer();
                    sb2.append("下载超时");
                    TextView tv2 = new TextView(ctx);
                    tv2.setTextSize(12);
                    tv2.setText(sb2);
                    tv2.setTextColor(Color.BLACK);
                    ftpTestDetail.addView(tv2);
                    updateTestResult();
                    drawLineChart();
                	break;
                }
            }
        };
        wlanManager = new WlanManager(ctx);
    	tm = new TelManager(ctx);
    }
    
    private String getTelNumber(){
    	TelManager telManager = new TelManager(ctx);
    	String phoneNumber = telManager.getPhoneNumber();
    	if (phoneNumber == null || phoneNumber.equals("")) {
    		phoneNumber = GlobalApp.ftp_GUID;
		}
    	return phoneNumber;
    }
    
    private void bindView(){
    	switch(GlobalApp.nowNetType) {
			case 1:
				llChart.setBackgroundResource(R.drawable.dialchart_ftpdown);
				break;
			case 2:
			case 3:
				llChart.setBackgroundResource(R.drawable.dialchart_ftpdown_tdgsm);
				break;
			default:
				break;
			}
    }
    
    private void initTestData() {
        if(wlanManager.checkNetworkType() == 1) {
        	fileNameUp = GlobalApp.fileNameWlanUp;
        	fileNameDown = GlobalApp.fileNameWlanDown;
        	simpleFTP.setFileSizeDown(GlobalApp.fileSizeWlanDown);
        } else {
        	if(tm.getNetworkType().equals(WlanManager.TD) || tm.getNetworkType().equals("HSUPA")) {
        		fileNameUp = GlobalApp.fileNameTDUp;
            	fileNameDown = GlobalApp.fileNameTDDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeTDDown);
        	} else {
        		fileNameUp = GlobalApp.fileNameGSMUp;
            	fileNameDown = GlobalApp.fileNameGSMDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeGSMDown);
        	}
        }
        //String path = "cc/ufinity/networkdiagnose/widget/ftp_test.png";
    	String path = "cc/ufinity/networkdiagnose/widget/" + fileNameUp;
        InputStream is = ctx.getClassLoader().getResourceAsStream(path); 
        // FileInputStream fis = new FileInputStream(is); 
        try {
            //ftm.setFileSize(is.available());
            File f = new File(localFilePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            FileOutputStream os = new FileOutputStream(localFilePath + fileNameUp);
            byte[] buffer = new byte[512];
            int ch = -1;
            while ((ch = is.read(buffer)) != -1) {
                os.write(buffer, 0, ch);
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initTestData2() {
        if(wlanManager.checkNetworkType() == 1) { 
        	fileNameDown = GlobalApp.fileNameWlanDown;
        	simpleFTP.setFileSizeDown(GlobalApp.fileSizeWlanDown);
        } else {
        	if(tm.getNetworkType().equals(WlanManager.TD) || tm.getNetworkType().equals("HSUPA") ) { 
            	fileNameDown = GlobalApp.fileNameTDDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeTDDown);
        	} else { 
            	fileNameDown = GlobalApp.fileNameGSMDown;
            	simpleFTP.setFileSizeDown(GlobalApp.fileSizeGSMDown);
        	}
        }
         
    }
    private void updateUploadProgress() {
        testedTimes++;
        testedTimesUp++;
        DecimalFormat df = new DecimalFormat("#0.00");
        float uploadSpeed = (float) simpleFTP.getUpY()[testedTimesUp-1];
        uploadSpeed *=8;
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(testedTimesUp).append("次上传速度为：").append(df.format(uploadSpeed));
        sb.append("Kb/s");
        TextView tv = new TextView(ctx);

        tv.setTextSize(12);
        tv.setText(sb.toString());
        tv.setTextColor(Color.BLACK);

        ftpTestDetail.addView(tv);
        //ftm.setTesting(false);
        
        //========================================== 
//        
        timesView.setText(testedTimes+"/"+COUNT * 2+"次");
        sucRateView.setText(df.format(uploadSpeed)+" Kb/s");
        rotateDialChart(lastSpeed,uploadSpeed);
        lastSpeed = uploadSpeed;
        setScrollViewDown(scrView);
    }

    private void updateDownloadProgress() {
    	testedTimes++;
    	testedTimesDown++;
        DecimalFormat df = new DecimalFormat("#0.00");
        float dwSpeed = (float) simpleFTP.getDwY()[testedTimesDown-1];
        dwSpeed *= 8;
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(testedTimesDown).append("次下载速度为：").append(df.format(dwSpeed));
        sb.append("Kb/s");
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(sb);
        tv.setTextColor(Color.BLACK);
        ftpTestDetail.addView(tv);
        //ftm.setTesting(false);
        
        timeRateView.setText(df.format(dwSpeed)+" Kb/s");
        timesView.setText(testedTimes+"/"+COUNT * 2+"次");
//        sucRateView.setText(df.format(uploadSpeed)+" kb/s");
        rotateDialChart(lastSpeed,dwSpeed);
        lastSpeed = dwSpeed;
        setScrollViewDown(scrView);
    }

    private void updateTestResult() {
        DecimalFormat df = new DecimalFormat("#0.00");
        double totalUpSpeed = 0.0;
        double totalDwSpeed = 0.0;
        for(int i=0; i<10; i++) {
        	totalUpSpeed += simpleFTP.getUpY()[i];
        }
        totalUpSpeed *=8;
        for(int i=0; i<10; i++) {
        	totalDwSpeed += simpleFTP.getDwY()[i];
        }
        totalDwSpeed *=8;
        double upSpeed = testedTimesUp==0? 0:totalUpSpeed / testedTimesUp;
        double downSpeed = testedTimesDown==0? 0:totalDwSpeed / testedTimesDown;
       
        StringBuffer s = new StringBuffer();
        s.append("总次数:").append(testedTimesUp + testedTimesDown);
        s.append(" 平均上传速度：").append(df.format(upSpeed)).append(" Kb/s");
        s.append(" 平均下载速度：").append(df.format(downSpeed)).append(" Kb/s");

        uploadTextId.setText("平均上传速度");
        downTextId.setText("平均下载速度");
        sucRateView.setText(df.format(upSpeed)+" Kb/s");
        timeRateView.setText(df.format(downSpeed)+" Kb/s");
        timesView.setText(testedTimes+"/"+ (testedTimesUp + testedTimesDown) +"次");
        TextView tv = new TextView(ctx);
        tv.setTextColor(Color.BLUE);
        tv.setTextSize(13);
        tv.setText(s);
        ftpTestDetail.addView(tv);
        setScrollViewDown(scrView);
    }

    public void statFtpTest() {
    	
        final FTPConfig ftp = this.getFTPConfig(ctx);
        
 System.err.println("FTP信息：" + ftp.address + "--" + ftp.port + "--" + ftp.userName + "--" + ftp.password); ////////// 
        if (ftp!=null && ftp.userName!=null && ftp.userName.length() > 0) {
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, ftpTestHandler);
            } else {
            	showMessageDialog(ctx, "正在连接FTP服务器...");
                new Thread() {
                    public void run() {
                    	 if (!logouting) {
       					  logouting = true;
       					  WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
       					  if(wifiInfo!= null && wifiInfo.getSSID() != null && wifiInfo.getSSID().equals(WlanManager.SSID_CMCC)){
       							WebAuthManager wManager = new WebAuthManager(ctx);
       							String  defaultUrl = ctx.getResources().getString(R.string.default_url);
       					        DBManager db = new DBManager(ctx);
       							Account config = db.getAccount();
       							String userName ="",pwd="";
       							if(null != config){ 
//       								String USER[]=AccountConfigWidget.stringAnalytical(config.userName);
//    								String PWD[]=AccountConfigWidget.stringAnalytical(config.password);
//    								userName = USER[0];
//       								pwd = PWD[0];
       								userName = config.userName;
       								pwd = config.password; 
       								wManager.auth(defaultUrl, userName, pwd);
       							}
       						}
       				    }
                    	simpleFTP = new SimpleFTP(ftp.address, ftp.port, 
             					ftp.userName, ftp.password, ftpTestHandler);
                        initTestData();
                        boolean tempStor = false;
                        //if (ftm.login(ftp.address, ftp.port, ftp.userName, ftp.password)) {
        	        	try {
        	                Thread.sleep(500);
        	            } catch (InterruptedException e) {}
            	        try {  
            	        	simpleFTP.connect();
            	        	try {
            	                Thread.sleep(500);
            	            } catch (InterruptedException e) {}
            	            try {
            	            	tempStor = simpleFTP.stor(localFilePath + fileNameUp, remotePathUp);
            	            }catch (Exception e) {
            	            	System.out.println("========= 文件上传： " + e.getMessage());
            	            	ftpTestHandler.sendEmptyMessage(simpleFTP.TIMEOUTUP);
            	            }
            	            
            	            try {
            	                Thread.sleep(500);
            	            } catch (InterruptedException e) {}
            	            if(SimpleFTP.testing) {
            	            	if(!tempStor){
            	            		double upX[] = simpleFTP.getUpX();
            	            		double upY[] = simpleFTP.getUpY();
            	            		int i = 1;
            	            		while(i < 3) {
            	            			simpleFTP = new SimpleFTP(ftp.address, ftp.port, 
                             					ftp.userName, ftp.password, ftpTestHandler);
                	            	 	simpleFTP.upX = upX;
                	            	 	simpleFTP.upY = upY;
                    	            	initTestData2();
                    	            	try {
                    	            		simpleFTP.connect();
                    	            		break;
                    	            	} catch(IOException e) {
                    	            		i++;
                    	            	}
            	            		}
            	            	}
            	            	try {
            	            		simpleFTP.get(localFilePath + fileNameDown, remotePathDown, fileNameDown);
            	            	} catch(IOException e) {
            	            		Message msg = ftpTestHandler.obtainMessage();
                    	        	msg.what = SimpleFTP.DOWNOVER;
                    	        	msg.sendToTarget();
            	            	}
            	            } else {
            	            	Message msg = ftpTestHandler.obtainMessage();
                	        	msg.what = SimpleFTP.TIMEOUTDOWN;
                	        	msg.sendToTarget();
            	            }
            	        } catch (IOException e) {
            	        	Message msg = ftpTestHandler.obtainMessage();
            	        	msg.what = MessageWhat.FTP_LOGIN_FAILED;
            	        	msg.sendToTarget();
            	            e.printStackTrace();
            	        } finally {
            	            try {
            	            	simpleFTP.disconnect();
            	            } catch (IOException e) {
            	                e.printStackTrace();
            	            }
            	        }
                    }
                }.start();
            }
        } else {
        	Message msg = ftpTestHandler.obtainMessage();
        	msg.what = MessageWhat.FTP_ACCOUNT_INVALID;
        	msg.sendToTarget();
        }
    }

    private void drawLineChart() {
        // ftm.logout();
    	double[] tempUp = simpleFTP.getUpY();
    	for(int i=0; i< tempUp.length; i++){
    		tempUp[i] *= 8;
    	}
    	double[] tempDw = simpleFTP.getDwY();
    	for(int i=0; i<tempDw.length; i++){
    		tempDw[i] *=8;
    	}
    	int max = getMax(tempUp)>getMax(tempDw)? getMax(tempUp):getMax(tempDw);
    	
        ChartManager cm = new ChartManager(ctx, 11, max);
        String chartTitle = "FTP上传(蓝线)/下载(绿线)";
        String[] lineTitles = new String[] { " ", " " };
        List<double[]> x = new ArrayList<double[]>(2);
        List<double[]> y = new ArrayList<double[]>(2);
        x.add(simpleFTP.getUpX());
        y.add(tempUp);
        x.add(simpleFTP.getDwX());
        y.add(tempDw);
        int[] colors = new int[] { Color.BLUE, Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        ftpTestChartLayout.addView(lineChart, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    }

    public void rotateDialChart(float last,float now){
		
    	//float start = last/128*18;
		float start = lastLast;
		float end = 0;
		if(GlobalApp.nowNetType ==1 ){
			//依据图片计算角度
			if(now >= 0 && now < 1024){
				end = now/256*18;
			}
			else if (now >= 1024 && now < 4*1024) {
				end = 1024/256*18 + (now-1024)/1024 *18; 
			}
			else if(now >= 4*1024 && now < 10*1024){
				end = 1024/256*18 + 3*1024/1024*18 + (now-4*1024)/2048 * 18;
			}else if ( now >= 10* 1024) {
				end = 180f;
			}
		}else if(GlobalApp.nowNetType==2 || GlobalApp.nowNetType ==3){
			if(now >= 0 && now < 1024){
				end = now/128*18;
			}else if(now >=1024 && now < 2048){
				end = 8 *18 + (now-1024)/512*18;
			}else if(now >= 248){
				end =180f;
			}
		}
		lastLast = end;
	// 旋转动画效果 
		 AnimationSet animation=new AnimationSet(true);
		 RotateAnimation rotateAnimation=new RotateAnimation(start, end,
				Animation.RELATIVE_TO_SELF, 1f,
				Animation.RELATIVE_TO_SELF, 0.25f);
	//	AlphaAnimation alpha=new AlphaAnimation(1, 0);
		/* ScaleAnimation acale=new ScaleAnimation(1, 0.1f, 1,0.1f,
				 Animation.RELATIVE_TO_SELF, 0.5f,
				 Animation.RELATIVE_TO_SELF, 0.5f);
			acale.setDuration(1000);
			animation.addAnimation(acale);*/
		 rotateAnimation.setDuration(500);
		 animation.addAnimation(rotateAnimation);
		 animation.setFillEnabled(true);
		 animation.setFillAfter(true);
	//	 alpha.setDuration(3000);
	//	 animation.addAnimation(alpha);
		 pointImageView.startAnimation(animation); 
	}
}
